package com.quwan.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.quwan.app.service.AppCircleService;
import com.quwan.app.vo.CircleDTO;
import com.quwan.app.vo.CircleNameDTO;
import com.quwan.common.BaseService;
import com.quwan.common.Check;
import com.quwan.common.enums.CommonStatus;
import com.quwan.common.exception.ExpCode;
import com.quwan.common.result.PageResult;
import com.quwan.config.yml.OssConfig;
import com.quwan.entity.*;
import com.quwan.manager.controller.dto.CircleCommentDto;
import com.quwan.mapper.*;
import com.quwan.utils.DateUtils;
import com.quwan.utils.Parse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author quan
 * @date 2022-03-20 18:03
 */
@Service
@RequiredArgsConstructor
public class AppCircleServiceImpl extends BaseService implements AppCircleService {
    private final TCircleTypeMapper circleTypeMapper;
    private final TCircleNameMapper circleNameMapper;
    private final TMemberCircleMapper memberCircleMapper;
    private final TCircleFollowMapper circleFollowMapper;
    private final TCircleCommentMapper circleCommentMapper;
    private final TCircleMapper circleMapper;
    private final TMemberMapper memberMapper;
    private final OssConfig ossConfig;

    @Override
    public List<TCircleType> getTypeList() {
        return circleTypeMapper
                .selectList(
                        new LambdaQueryWrapper<TCircleType>()
                                .select(TCircleType::getId, TCircleType::getTypeName)
                                .eq(TCircleType::getStatus, CommonStatus.NORMAL.getType())
                );
    }

    @Override
    public PageResult<CircleNameDTO> getNameList(int pageNo, int pageSize, String id, String mId) {
        Page<CircleNameDTO> res = circleNameMapper.selectNameList(new Page<>(pageNo, pageSize), id, mId);
        res.getRecords().stream().forEach(each -> {
            String url = each.getHeaderUrl();
            String backUrl = each.getBackUrl();
            each.setHeaderUrl(StringUtils.isBlank(url) ? url : ossConfig.getHostname() + "/" + url);
            each.setBackUrl(StringUtils.isBlank(backUrl) ? backUrl : ossConfig.getHostname() + "/" + backUrl);
        });
        return new PageResult<CircleNameDTO>()
                .setRecords(res.getRecords())
                .setTotal(res.getTotal())
                .setSize(res.getSize())
                .setCurrent(res.getCurrent())
                .setPages(res.getPages());

    }

    @Override
    public boolean followCircle(String mId, String id, Integer status) {
        return memberCircleMapper.followOrCancel(mId + id, mId, id, status) != 0;

    }

    @Override
    public PageResult<TCircleName> followerCircleList(String mId, int pageNo, int pageSize) {
        Page<TCircleName> res = circleNameMapper.selectPage(
                new Page<>(pageNo, pageSize),
                new LambdaQueryWrapper<TCircleName>()
                        .exists("select 1 from t_member_circle where  m_id = {0} and circle_name_id =t_circle_name.id and status = {1} ", mId, CommonStatus.NORMAL.getType())
        );
        res.getRecords().stream().forEach(each -> {
            String url = each.getHeaderUrl();
            each.setHeaderUrl(StringUtils.isBlank(url) ? "" : ossConfig.getHostname() + "/" + url)
                    .setBackUrl(StringUtils.isBlank(each.getBackUrl()) ? "" : ossConfig.getHostname() + "/" + each.getBackUrl());
        });
        return new PageResult<TCircleName>()
                .setRecords(res.getRecords())
                .setPages(res.getPages())
                .setCurrent(res.getCurrent())
                .setSize(res.getSize())
                .setTotal(res.getTotal());
    }

    @Override
    public boolean followCircleContent(String mId, String id, Integer status) {
        return circleFollowMapper.followOrCancel(mId + id, mId, id, status) != 0;
    }

    @Override
    public PageResult<CircleDTO> contentList(String mId, int pageNo, int pageSize, String type, String id) {
        Page<CircleDTO> res = circleMapper.selectContentList(new Page<>(pageNo, pageSize), mId, type, id);
        return new PageResult<CircleDTO>()
                .setTotal(res.getTotal())
                .setSize(res.getSize())
                .setCurrent(res.getSize())
                .setPages(res.getPages())
                .setRecords(res.getRecords().stream().map(m ->
                        {
                            List<String> urls =
                                    strToList(",", m.getImgUrl())
                                            .stream()
                                            .map(url -> StringUtils.isBlank(url) ? url : ossConfig.getHostname() + "/" + url)
                                            .collect(Collectors.toList());
                            String memberUrl = m.getMemberUrl();
                            m.setImgUrls(urls);
                            m.setMemberUrl(StringUtils.isBlank(memberUrl) ? memberUrl : ossConfig.getHostname() + "/" + memberUrl);
                            Long minutes = DateUtils.computeMinutes(m.getAddTime(), LocalDateTime.now());
                            if (minutes < 60)
                                m.setReplyTime("回复于" + (minutes + 1) + "分钟前");
                            else if (minutes < 1440)
                                m.setReplyTime("回复于" + ((minutes + 1) / 60) + "小时前");
                            else
                                m.setReplyTime("回复于" + ((minutes + 1) / 1440) + "天前");
                            return m;
                        }
                ).collect(Collectors.toList()));
    }

    @Override
    public boolean publishCircle(String mId, String id, String content, String imgs) {
        TCircleName circleName = circleNameMapper.selectById(id);
        TMember member = memberMapper.selectOne(new QueryWrapper<>(new TMember().setId(Parse.toLong(mId))));
        Check.notNull(circleName, ExpCode.DATA_SELECT_NULL);
        Check.notNull(member, ExpCode.DATA_SELECT_NULL);
        int row = circleMapper.insert(
                new TCircle()
                        .setCircleNameId(circleName.getId())
                        .setCircleTypeId(Parse.toLong(circleName.getCircleTypeId()))
                        .setContent(content)
                        .setImgUrl(imgs)
                        .setCreateTime(LocalDateTime.now())
                        .setCreateUserId(Parse.toLong(mId))
                        .setStatus(CommonStatus.NORMAL.getType())
                        .setCreateUserName(member.getNickName())

        );
        return row == 1;
    }

    @Override
    public CircleDTO getCircleDetail(String id, String mId) {
        TCircle circle = circleMapper.selectById(id);
        Check.notNull(circle, ExpCode.DATA_SELECT_NULL);
        Long createUserId = circle.getCreateUserId();
        TMember member = memberMapper.selectOne(new QueryWrapper<>(new TMember().setId(createUserId)));
        Check.notNull(member, ExpCode.DATA_SELECT_NULL);
        CircleDTO dto = new CircleDTO();
        return dto.setMId(member.getId().toString())
                .setContent(circle.getContent())
                .setNickname(member.getNickName())
                .setAddTime(circle.getCreateTime())
                .setFollow(StringUtils.isNotBlank(mId) && circleFollowMapper.selectCount(new QueryWrapper<>(new TCircleFollow().setId(mId + id).setStatus(CommonStatus.NORMAL.getType()))) != 0)
                .setMemberUrl(StringUtils.isBlank(member.getImgUrl()) ? "" : ossConfig.getHostname() + "/" + member.getImgUrl())
                .setId(circle.getId().toString())
                .setImgUrls(strToList(",", circle.getImgUrl()).stream().map(m -> ossConfig.getHostname() + "/" + m).collect(Collectors.toList()));


    }

    @Override
    public PageResult<CircleCommentDto> getCircleCommentList(int pageNo, int pageSize, String id) {
//        Page<TCircleComment> res = circleCommentMapper
//                .selectPage(
//                        new Page<>(pageNo, pageSize),
//                        new LambdaQueryWrapper<TCircleComment>()
//                                .eq(TCircleComment::getCircleId, id)
//                                .orderByDesc(TCircleComment::getCreateTime)
//                );
        Page<CircleCommentDto> res = circleCommentMapper.selectCommentList(new Page<>(pageNo, pageSize), id);
        res.getRecords().stream().forEach(f ->
                    f.setImage(StringUtils.isBlank(f.getImage()) ? "" : ossConfig.getHostname() + "/" + f.getImage()));
        return new PageResult<CircleCommentDto>()
                .setRecords(res.getRecords())
                .setPages(res.getPages())
                .setCurrent(res.getCurrent())
                .setSize(res.getSize())
                .setTotal(res.getTotal());
    }

    @Override
    public boolean circleComment(String id, String content, String mId) {
        return circleCommentMapper.insert(
                new TCircleComment()
                        .setCircleId(Parse.toLong(id))
                        .setContent(content)
                        .setCreateTime(LocalDateTime.now())
                        .setMId(Parse.toLong(mId))
        ) == 1;
    }
}
